<?php

class UserManager
{
	public static function Search($search)
	{
		$bean = R::find('user', 'login LIKE \'%' . $search . '%\' or fullname LIKE \'%' . $search . '%\'');
		return $bean;
	}
	
	public static function GetUser( $user )
	{
		$bean = R::findOne('user', 'login=\'' . $user . '\'');
		if($bean == false) $bean = null;
		return $bean;
	}
	
	public static function DeleteUser($user)
	{
		if($bean = R::findOne('user', 'login=\'' . $user . '\''))
		{
			return R::trash($bean);
		}
		return false;
	}
	
	public static function Authenticate($user, $password)
	{
		if($bean = R::findOne('user', 'login=\'' . $user . '\''))
		{
			$salt = $bean->passwordsalt;
			$hash = $bean->passwordhash;
			$authHash = PasswordHasher::GenerateHash( $password, $salt );
			return $authHash == $hash;
		}
		return false;
	}
	
	public static function Signup($user, $password, $fullName, $email)
	{
		if(R::findOne('user', 'login=\'' . $user . '\''))return false; 
		$bean = R::dispense('user');
		$bean->passwordsalt = PasswordHasher::GenerateSalt( );
		$bean->passwordhash = PasswordHasher::GenerateHash( $password, $bean->passwordsalt );
		$bean->login = $user;
		$bean->fullname = $fullName;
		$bean->email = $email;
		$bean->location = '';
		$bean->birthdate = '';
		$bean->isemailconfirmed = false;
		$bean->receiveemail = false;
		return R::store($bean);
	}
	
	public static function ConfirmEmail($user, $email)
	{
		if($bean = R::findOne('user', 'login=? and email=?', array($user, $email)))
		{
			$bean->isemailconfirmed = true;
			R::store($bean);
			return true;
		}
		return false;
	}
	
	public static function AddFacebook($user, $facebook)
	{
		$user = R::findOne('user', 'login=\'' . $user . '\'');
		$user->facebook = $facebook;
		R::store($user);
		return true;	
	}
	
	public static function GetUserByFacebook($facebook)
	{
		$res = R::getCell('select login from user where facebook=?', array($facebook));
		if($res == null)
			return null;
		return self::GetUser( $res );
	}
}